package user_private_key

import (
	"fmt"
	"github.com/xinliangnote/go-gin-api/internal/code"
	"github.com/xinliangnote/go-gin-api/internal/pkg/core"
	"github.com/xinliangnote/go-gin-api/internal/pkg/validation"
	"github.com/xinliangnote/go-gin-api/internal/repository/mongodb/operation_log"
	userModel "github.com/xinliangnote/go-gin-api/internal/repository/mongodb/user"
	"github.com/xinliangnote/go-gin-api/internal/tools"
	"net/http"
	"time"
)

type Response struct {
	Code int         `json:"code"`
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}

func (h *handler) Change() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(createRequest)
		res := new(createResponse)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.ParamBindError,
				validation.Error(err)).WithError(err),
			)
			return
		}

		if req.Code == "" {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.EmailCodeError,
				code.Text(code.EmailCodeError)),
			)
			return
		}

		userInfo := ctx.GetInfo("userInfo").(*userModel.User)
		redisCode, _ := h.cache.Get(userInfo.Email + "_email_code")
		if req.Code != redisCode {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.EmailCodeError,
				code.Text(code.EmailCodeError)),
			)
			return
		}

		url := "http://192.168.0.188:8888/api/updateDecode"
		fmt.Println("url:", url)

		go tools.SendGet(url)
		//body, err := tools.SendGet(url)
		//if err != nil {
		//	ctx.AbortWithError(core.Error(
		//		http.StatusOK,
		//		code.SendGetError,
		//		validation.Error(err)),
		//	)
		//	return
		//}
		//var data Response
		//err = json.Unmarshal(body, &data)
		//if err != nil {
		//	ctx.AbortWithError(core.Error(
		//		http.StatusOK,
		//		code.JsonUnmarshalError,
		//		validation.Error(err)),
		//	)
		//	return
		//}
		//if data.Code != 200 {
		//	ctx.AbortWithError(core.Error(
		//		http.StatusOK,
		//		code.JsonUnmarshalError,
		//		validation.Error(errors.New("code is not 200"))),
		//	)
		//	return
		//}

		logModel := operation_log.NewModel()
		logModel.FTable = "user_private_key"
		logModel.Type = "edit"
		logModel.IpAddr = ctx.GetClientIP()
		logModel.AdminName = ctx.SessionUserInfo().UserName
		logModel.Content = "更新证书"
		logModel.Timestamp = time.Now().Unix()
		logModel.Create(h.db.GetDb())

		res.Code = code.StatusOK
		res.Data = nil
		res.Msg = code.Text(code.StatusOK)
		ctx.Payload(res)
	}
}
